<template>
    <div class="blog">
        <div class="blog-header">
            <h1>博客文章</h1>
            <p>探索我们的最新文章和思考</p>

            <div class="blog-filters">
                <div class="search-box">
                    <input
                        type="text"
                        v-model="searchQuery"
                        placeholder="搜索文章..."
                        @input="filterPosts"
                    />
                </div>

                <div class="category-filter">
                    <select v-model="selectedCategory" @change="filterPosts">
                        <option value="">所有分类</option>
                        <option
                            v-for="category in categories"
                            :key="category.id"
                            :value="category.id"
                        >
                            {{ category.name }}
                        </option>
                    </select>
                </div>
            </div>
        </div>

        <div v-if="loading" class="loading-container">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
        </div>

        <div v-else class="blog-content">
            <div class="posts-container">
                <div
                    v-for="post in filteredPosts"
                    :key="post.id"
                    class="blog-post"
                >
                    <div
                        class="post-image"
                        :style="{ backgroundImage: `url(${post.image})` }"
                    ></div>
                    <div class="post-details">
                        <div class="post-meta">
                            <span class="post-date">{{ post.date }}</span>
                            <span class="post-category">{{
                                getCategoryName(post.categoryId)
                            }}</span>
                        </div>
                        <h2 class="post-title">{{ post.title }}</h2>
                        <p class="post-excerpt">{{ post.excerpt }}</p>
                        <div class="post-footer">
                            <router-link
                                :to="`/blog/${post.id}`"
                                class="read-more-btn"
                            >
                                阅读全文
                            </router-link>
                        </div>
                    </div>
                </div>

                <div
                    v-if="filteredPosts.length === 0 && !loading"
                    class="no-posts"
                >
                    <p>没有找到符合条件的文章</p>
                </div>
            </div>

            <div class="blog-sidebar">
                <div class="sidebar-section categories-section">
                    <h3>文章分类</h3>
                    <ul class="category-list">
                        <li
                            v-for="category in categories"
                            :key="category.id"
                            :class="{
                                active: selectedCategory === category.id,
                            }"
                            @click="
                                selectedCategory = category.id;
                                filterPosts();
                            "
                        >
                            {{ category.name }} ({{ category.count }})
                        </li>
                    </ul>
                </div>

                <div class="sidebar-section popular-posts">
                    <h3>热门文章</h3>
                    <ul class="popular-posts-list">
                        <li v-for="post in popularPosts" :key="post.id">
                            <router-link :to="`/blog/${post.id}`">
                                {{ post.title }}
                            </router-link>
                            <span class="post-date">{{ post.date }}</span>
                        </li>
                    </ul>
                </div>

                <div class="sidebar-section tags-section">
                    <h3>标签云</h3>
                    <div class="tags-cloud">
                        <span
                            v-for="tag in tags"
                            :key="tag.id"
                            class="tag"
                            :style="{
                                fontSize: `${tag.weight * 0.8 + 0.8}rem`,
                            }"
                            @click="filterByTag(tag.id)"
                        >
                            {{ tag.name }}
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRoute } from "vue-router";
import { postApi, categoryApi, tagApi } from "../api";

const route = useRoute();
const loading = ref(true);
const error = ref(null);

// 数据
const posts = ref([]);
const categories = ref([]);
const tags = ref([]);

// 搜索和筛选
const searchQuery = ref("");
const selectedCategory = ref("");
const selectedTag = ref(null);

// 获取数据
const fetchData = async () => {
    loading.value = true;
    error.value = null;

    try {
        // 获取文章数据
        const postsResponse = await postApi.getPosts();
        posts.value = postsResponse.data;

        // 获取分类数据
        const categoriesResponse = await categoryApi.getCategories();
        categories.value = categoriesResponse.data;

        // 获取标签数据
        const tagsResponse = await tagApi.getTags();
        tags.value = tagsResponse.data;

        // 初始化筛选后的文章列表
        filteredPosts.value = [...posts.value];

        // 检查URL参数
        const id = route.params.id;
        if (id) {
            // 如果URL中有ID参数，可以做一些处理
            console.log("文章ID:", id);
        }

        const query = route.query;
        if (query.category) {
            selectedCategory.value = parseInt(query.category);
            filterPosts();
        }

        if (query.tag) {
            selectedTag.value = parseInt(query.tag);
            filterPosts();
        }
    } catch (err) {
        console.error("获取数据失败:", err);
        error.value = "获取数据失败，请稍后重试";
    } finally {
        loading.value = false;
    }
};

// 在组件挂载时获取数据
onMounted(fetchData);

// 热门文章（基于浏览量排序）
const popularPosts = computed(() => {
    return [...posts.value]
        .sort((a, b) => (b.views || 0) - (a.views || 0))
        .slice(0, 3);
});

const filteredPosts = ref([]);

// 筛选文章
const filterPosts = () => {
    filteredPosts.value = posts.value.filter((post) => {
        // 搜索匹配
        const matchesSearch =
            searchQuery.value === "" ||
            post.title
                .toLowerCase()
                .includes(searchQuery.value.toLowerCase()) ||
            post.excerpt
                .toLowerCase()
                .includes(searchQuery.value.toLowerCase());

        // 分类匹配
        const matchesCategory =
            selectedCategory.value === "" ||
            post.categoryId === selectedCategory.value;

        // 标签匹配
        const matchesTag =
            selectedTag.value === null ||
            (post.tags && post.tags.includes(selectedTag.value));

        return matchesSearch && matchesCategory && matchesTag;
    });
};

// 按标签筛选
const filterByTag = (tagId) => {
    selectedTag.value = selectedTag.value === tagId ? null : tagId;
    filterPosts();
};

// 获取分类名称的辅助函数
const getCategoryName = (categoryId) => {
    const category = categories.value.find((cat) => cat.id === categoryId);
    return category ? category.name : "";
};
</script>

<style scoped>
.blog {
    padding-bottom: 60px;
}

.blog-header {
    margin-bottom: 40px;
}

.blog-header h1 {
    font-size: 2.2rem;
    margin-bottom: 10px;
}

.blog-header p {
    color: #777;
    margin-bottom: 30px;
}

.blog-filters {
    display: flex;
    gap: 20px;
    margin-bottom: 30px;
}

.search-box {
    flex: 1;
}

.search-box input {
    width: 100%;
    padding: 12px 15px;
    border-radius: 4px;
}

.category-filter select {
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: white;
    min-width: 150px;
}

.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 50px 0;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-radius: 50%;
    border-top-color: #3498db;
    animation: spin 1s ease-in-out infinite;
    margin-bottom: 15px;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

.blog-content {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 40px;
}

.blog-post {
    display: flex;
    margin-bottom: 40px;
    background-color: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.blog-post:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.post-image {
    width: 300px;
    background-size: cover;
    background-position: center;
}

.post-details {
    flex: 1;
    padding: 25px;
}

.post-meta {
    display: flex;
    gap: 15px;
    margin-bottom: 15px;
    font-size: 0.9rem;
    color: #777;
}

.post-category {
    color: #3498db;
}

.post-title {
    font-size: 1.5rem;
    margin-bottom: 15px;
}

.post-excerpt {
    color: #555;
    margin-bottom: 20px;
    line-height: 1.6;
}

.post-footer {
    margin-top: 20px;
}

.read-more-btn {
    display: inline-block;
    padding: 8px 20px;
    background-color: #3498db;
    color: white;
    border-radius: 4px;
    font-weight: 500;
    transition: background-color 0.3s ease;
}

.read-more-btn:hover {
    background-color: #2980b9;
}

.no-posts {
    padding: 40px;
    text-align: center;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.blog-sidebar {
    display: flex;
    flex-direction: column;
    gap: 30px;
}

.sidebar-section {
    background-color: white;
    padding: 25px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.sidebar-section h3 {
    font-size: 1.2rem;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}

.category-list {
    list-style: none;
}

.category-list li {
    padding: 8px 0;
    cursor: pointer;
    transition: color 0.3s ease;
}

.category-list li:hover,
.category-list li.active {
    color: #3498db;
}

.popular-posts-list {
    list-style: none;
}

.popular-posts-list li {
    margin-bottom: 15px;
}

.popular-posts-list a {
    display: block;
    margin-bottom: 5px;
}

.popular-posts-list .post-date {
    font-size: 0.8rem;
    color: #777;
}

.tags-cloud {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.tag {
    display: inline-block;
    padding: 5px 10px;
    background-color: #f5f5f5;
    border-radius: 20px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.tag:hover {
    background-color: #e0e0e0;
}

.tag.active {
    background-color: #3498db;
    color: white;
}

@media (max-width: 768px) {
    .blog-content {
        grid-template-columns: 1fr;
    }

    .blog-post {
        flex-direction: column;
    }

    .post-image {
        width: 100%;
        height: 200px;
    }
}
</style>
